<template>
  <SelectionDialog ref="selectionDialogRef" v-model="dialogVisible" :config="dimensionConfig" :optional-data="optionalDimensions"
    :selected-data="selectedDimensions" :data-loading="dataLoading" width="1015px" :confirm-loading="dimensionLoading" @confirm="handleConfirm"
    @cancel="handleCancel" />
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, h } from 'vue'
import { ElMessage, ElTooltip, ElIcon } from 'element-plus'
import { $t } from '@vben/locales'
import SelectionDialog from './selection-dialog.vue'
import { getReviewDimensionPageApi, updateCompTrackStatusApi } from '#/api/competition/track-mgr'
import { Info } from '@vben/icons'
// 评审维度数据接口
interface Dimension {
  id: number | string
  name: string
  description?: string
  weight?: number
  maxScore?: number
  [key: string]: any
}

// Props 定义
interface Props {
  modelValue: boolean
  trackId?: string
  selectedDimensionIds?: (number | string)[]
  mode?: 'add' | 'edit' // 新增模式参数
}

const props = withDefaults(defineProps<Props>(), {
  selectedDimensionIds: () => [],
  mode: 'add'
})

// Emits 定义
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': []
  'cancel': []
}>()

const confirmLoading = ref(false)

// 评审维度选择配置 - 使用计算属性动态设置标题
const dimensionConfig = computed(() => ({
  title: props.mode === 'edit'
    ? $t('trackMgr.editDimensionsTitle')
    : $t('trackMgr.setDimensionsTitle'),
  searchPlaceholder: $t('userMessage.searchPlaceholder'),
  columns: [
    { prop: 'examine', label: $t('trackMgr.examinePoint'), minWidth: '88px' },
    {
      prop: 'evaluate',
      label: $t('trackMgr.evaluateDimension'),
      minWidth: '200px',
      render: (row: Dimension) => {
        return h('div', { class: 'flex justify-between items-center' }, [
          h('span', {
            class: 'flex-1 truncate mr-2',
            title: row.evaluate // 原生 title 属性作为备用
          }, row.evaluate),
          // 只有当 row.instructions 有内容时才显示图标和 tooltip
          row.instructions ? h(ElTooltip, {
            class: 'box-item',
            effect: 'dark',
            content: row.instructions,
            placement: 'top'
          }, {
            default: () => h(ElIcon, { class: 'w-[14px] h-[14px] text-gray-400 flex-shrink-0' }, {
              default: () => h(Info)
            })
          }) : null
        ])
      }
    },
    { prop: 'score', label: $t('trackMgr.examineScore'), minWidth: '80px', align: 'right' },
  ],
  type: 'dimension' as const
}))

// 响应式数据
const loading = ref(false)
const dimensionLoading = ref(false)
const dataLoading = ref(false) // 数据加载状态
const allDimensions = ref<Dimension[]>([])
const selectionDialogRef = ref() // 选择对话框引用

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 可选评审维度列表（排除已选的）
const optionalDimensions = computed(() => {
  return allDimensions.value.filter(dimension =>
    !props.selectedDimensionIds.includes(dimension.id)
  )
})

// 已选评审维度列表
const selectedDimensions = computed(() => {
  return allDimensions.value.filter(dimension =>
    props.selectedDimensionIds.includes(dimension.id)
  )
})

// 获取所有评审维度数据
const fetchAllDimensions = async () => {
  loading.value = true
  dataLoading.value = true

  // 通知子组件开始加载数据
  if (selectionDialogRef.value) {
    selectionDialogRef.value.setOptionalLoading(true)
  }

  try {
    const response = await getReviewDimensionPageApi(props.trackId)
    allDimensions.value = response.data || []
  } catch (error) {
    ElMessage.error('获取评审维度数据失败，请重试')
    allDimensions.value = []
  } finally {
    loading.value = false
    dataLoading.value = false
    // 通知子组件结束加载数据
    if (selectionDialogRef.value) {
      selectionDialogRef.value.setOptionalLoading(false)
    }
  }
}

// 确认选择
const handleConfirm = async (selectedItems: any[]) => {
  console.log(selectedItems, selectedItems.map(dimension => dimension.id), "selectedItems");
  confirmLoading.value = true
  if (!props.trackId) {
    ElMessage.error($t('trackMgr.trackIdRequired'))
    return
  }

  dimensionLoading.value = true
  const paramData = {
    id: props.trackId,
    reviewDimensionList: selectedItems.map(dimension => dimension.id)
  }

  try {
    await updateCompTrackStatusApi(paramData).then(() => {
      ElMessage.success($t('trackMgr.dimensionSetSuccess'))
      emit('confirm')
      emit('update:modelValue', false)
    })
  } catch (error) {
    ElMessage.error($t('trackMgr.dimensionSetFailed'))
    console.error($t('trackMgr.dimensionSetFailed'), error)
  } finally {
    dimensionLoading.value = false
    confirmLoading.value = false
  }
}

// 取消选择
const handleCancel = () => {
  emit('cancel')
  emit('update:modelValue', false)
}

// 监听弹窗打开，获取数据和清空数据
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    fetchAllDimensions()
  } else {
    // 弹窗关闭时清空子组件数据
    if (selectionDialogRef.value) {
      selectionDialogRef.value.clearAllData()
    }
  }
})

// 组件挂载时获取数据
onMounted(() => {
  if (props.modelValue) {
    fetchAllDimensions()
  }
})
</script>
